package com.example.mymusic;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;


import java.util.ArrayList;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;


/**
 * @author xky
 */
public class MusicActivity extends AppCompatActivity implements View.OnClickListener {
    private final String TAG = "MusicActivityLog";
    private ImageView btnPlay;
    private SeekBar seekBar;
    private TextView tvTitle, tvSinger, tvCurTime, tvTotalTime;


    private int currentPosition = 0;
    public static boolean mMusicActivity = false;
    private MyConnection conn = null;
    private MusicService.MyBinder musicService = null;

    /**
     * 为0即没播放过，需要play转动；
     * 为1即暂停过，需要resume转动
     */
    private final int yesFirstPlay = 0;
    private final int noFirstPlay = 1;
    private int firstPlay = yesFirstPlay;


    private MyReceiver myReceiver;
    private ImageView state;

    private ImageView imageBig;
    private CircleImageView image_small;

    private ObjectAnimator objectAnimator;

    MySqLiteOpenHelper helper;

    private class MyConnection implements ServiceConnection {


        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected: ");
            musicService = (MusicService.MyBinder) service;
            //注册意图过滤器，接受符合的广播
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("update_ui");
            registerReceiver(myReceiver, intentFilter);
            updateUI();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mMusicActivity = true;
        //注册广播接收器
        myReceiver = new MyReceiver();
        helper = new MySqLiteOpenHelper(this, "media_player_data.db", null, 1);

        //调用service的方法，管理应用程序的系统状态，两个应用间的跳转
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        assert am != null;
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        Log.i(TAG, "onCreate: " + cn.getPackageName());
        Log.i(TAG, "onCreate: " + cn.getClassName());

        //取得内容
        Bundle bundle = getIntent().getExtras();
        //创建intent对象，要跳转去MusicService

        Intent intent = new Intent(this, MusicService.class);
        //将要传递的值附加到Intent对象,bundle
        assert bundle != null;
        intent.putExtras(bundle);
        conn = new MyConnection();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        bindService(intent, conn, BIND_AUTO_CREATE);
        init();

        helper = new MySqLiteOpenHelper(MusicActivity.this, "media_player_data.db", null, 1);
        helper.getWritableDatabase();

    }

    /**
     * 接收到广播就更新界面
     */
    public class MyReceiver extends BroadcastReceiver {


        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive: onReceive");
            updateUI();
        }
    }

    /**
     * 更新详情界面各项内容
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void updateUI() {
        Log.i(TAG, "updateUI: " + MusicService.musicState);

        //根据播放状态，更改按钮图标
        if (musicService.getMusicState()) {
            Log.i(TAG, "updateUI: +++++++++++++++++++++++++");
            btnPlay.setImageResource(R.drawable.pause);

            if (firstPlay == yesFirstPlay) {
                objectAnimator.start();
                image_small.play();
            } else {
                objectAnimator.resume();
                image_small.resume();
            }
            firstPlay = noFirstPlay;
            //控制进度条，开始动
            handlerSeekBar.post(updateThread);
        } else {
            Log.i(TAG, "updateUI: ------------------------");
            //控制进度条，不许动
            handlerSeekBar.removeCallbacks(updateThread);
            if (musicService.getMediaPlayer() == null) {
                currentPosition = musicService.getMDuration();
            } else {
                currentPosition = musicService.getMediaPlayer().getCurrentPosition();
            }
            btnPlay.setImageResource(R.drawable.start);
            objectAnimator.pause();
            image_small.pause();

        }

        //更改模式显示内容
        switch (musicService.getState()) {
            case MusicService.ORDER_PLAY:
                state.setImageResource(R.drawable.order_play);
                break;
            case MusicService.SINGLE_CYCLE:
                state.setImageResource(R.drawable.single_cycle);
                break;
            case MusicService.RANDOM_PLAY:
                state.setImageResource(R.drawable.random_play);
                break;
            default:
                break;
        }

        //更改歌名，进度条
        tvTitle.setText(musicService.getListMusic().get(musicService.getMPosition()).name);
        tvTitle.setSelected(true);
        tvSinger.setText(musicService.getListMusic().get(musicService.getMPosition()).singer);
        tvSinger.setSelected(true);
        tvTotalTime.setText(Utils.formatTime(musicService.getListMusic().get(musicService.getMPosition()).duration));
        tvCurTime.setText(Utils.formatTime(currentPosition));
        image_small.setImageBitmap(MusicService.bitmap);
        seekBar.setMax(musicService.getListMusic().get(musicService.getMPosition()).duration);
        seekBar.setProgress(currentPosition);
    }


    /**
     * 在本activity重新获得焦点时，进行界面更新
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onResume() {
        firstPlay = yesFirstPlay;
        super.onResume();
        Log.i(TAG, "onResume");
        if (musicService != null) {
            updateUI();
        }
    }

    /**
     * 创建handler对象
     * 将要执行的操作写在线程对象的run方法中
     * 歌曲当前时间和进度条异步更新
     */
    Handler handlerSeekBar = new Handler();
    Runnable updateThread = new Runnable() {
        @Override
        public void run() {

            if (MusicService.mediaPlayer == null) {
                //如果没有绑定成功service的话，获取到service的方法的话，以防万一
                seekBar.setProgress(MusicService.m_duration);
                currentPosition = MusicService.m_duration;
                //在run方法内部，执行postDelayed方法，延迟多少毫秒后开始
            } else {
                seekBar.setProgress(MusicService.mediaPlayer.getCurrentPosition());
                currentPosition = MusicService.mediaPlayer.getCurrentPosition();
                //在run方法内部，执行postDelayed方法，延迟多少毫秒后开始
            }
            tvCurTime.setText(Utils.formatTime(currentPosition));
            handlerSeekBar.postDelayed(updateThread, 100);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.local_music_bottom_iv_last:
                musicService.getService().pre();
                objectAnimator.start();
                image_small.play();
                firstPlay = yesFirstPlay;
                break;

            case R.id.local_music_bottom_iv_next:
                musicService.getService().next();
                objectAnimator.start();
                image_small.play();
                firstPlay = yesFirstPlay;
                break;

            case R.id.local_music_bottom_iv_play:
                musicService.getService().play();
                if (musicService.getMediaPlayer().isPlaying()) {
                    objectAnimator.pause();
                    image_small.pause();
                } else {
                    if (firstPlay == yesFirstPlay) {
                        objectAnimator.start();
                        image_small.play();
                    } else {
                        objectAnimator.resume();
                        image_small.resume();
                    }
                    firstPlay = noFirstPlay;
                }
                break;

            case R.id.local_music_bottom_state:
                String state;
                musicService.updateState();
                if (MusicService.state == 0) {
                    state = this.getApplicationContext().getResources().getString(R.string.ORDER_PLAY);
                } else if (MusicService.state == 1) {
                    state = this.getApplicationContext().getResources().getString(R.string.SINGLE_CYCLE);
                } else {
                    state = this.getApplicationContext().getResources().getString(R.string.RANDOM_PLAY);
                }
                ToastUtils.showText(this, state);
                break;

            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy");
        mMusicActivity = false;

        //删除指定的Runnable对象，使线程对象停止运行
        handlerSeekBar.removeCallbacks(updateThread);

        //解绑service
        unbindService(conn);

        //unregisterReceiver(MyFlowerView.myReceiver);

        //取消广播接收器
        unregisterReceiver(myReceiver);

        super.onDestroy();
    }

    @SuppressLint({"WrongViewCast", "ObjectAnimatorBinding"})
    private void init() {
        Log.i(TAG, "init");
        ImageView btnPre = findViewById(R.id.local_music_bottom_iv_last);
        ImageView btnNext = findViewById(R.id.local_music_bottom_iv_next);
        btnPlay = findViewById(R.id.local_music_bottom_iv_play);
        state = findViewById(R.id.local_music_bottom_state);
        seekBar = findViewById(R.id.sb_progress);
        tvTitle = findViewById(R.id.tv_song_name);
        tvSinger = findViewById(R.id.tv_song_singer);
        tvCurTime = findViewById(R.id.tv_progress_current);
        tvTotalTime = findViewById(R.id.tv_progress_total);
        imageBig = findViewById(R.id.iv_disk);
        image_small = findViewById(R.id.iv_album_image);
        firstPlay = yesFirstPlay;


        btnPlay.setOnClickListener(this);
        btnNext.setOnClickListener(this);
        btnPre.setOnClickListener(this);
        state.setOnClickListener(this);

        objectAnimator = ObjectAnimator.ofFloat(imageBig, "rotation", 0f, 360f);
        objectAnimator.setDuration(30000);
        objectAnimator.setInterpolator(new LinearInterpolator());
        objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        objectAnimator.setRepeatMode(ObjectAnimator.RESTART);


        //进度条拖动事件监听
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.Q)
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    musicService.getMediaPlayer().seekTo(progress);
                    tvCurTime.setText(Utils.formatTime(musicService.getMediaPlayer().getCurrentPosition()));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

    }

}
